﻿using Furion.DatabaseAccessor;
using Furion.TaskScheduler;
using Microsoft.EntityFrameworkCore;
using Queer.AutoJob.Core.Entity;
using System;

namespace Queer.AutoJob.Core.EntityListener
{
    public class AutoJobEntityListener : IEntityChangedListener<AutoJobEntity>
    {
        public void OnChanged(AutoJobEntity newEntity, AutoJobEntity oldEntity, DbContext dbContext, Type dbContextLocator, EntityState state)
        {
            if (oldEntity == null)
                return;

            // 任务取消
            if ((oldEntity.IsDelete == false && newEntity.IsDelete == true) || 
                (oldEntity.JobStatus == 1 && newEntity.JobStatus == 0))
            {
                JobCenter.JobCancel(oldEntity);
                return;
            }

            // 任务继续
            if ((oldEntity.IsDelete == true && newEntity.IsDelete == false) ||
                (oldEntity.JobStatus == 0 && newEntity.JobStatus == 1))
            {
                JobCenter.JobStart(oldEntity);
                return;
            }

            // 任务继续，但CRON改变，重载任务。（注意：如果状态就发生了改变，上面就会执行，无需担心）
            if (oldEntity.IsDelete == false && newEntity.IsDelete.GetValueOrDefault() == false && oldEntity.JobStatus == 1 && newEntity.JobStatus == 1 &&
                   (newEntity.CronExpression != oldEntity.CronExpression ||
                    newEntity.JobName != oldEntity.JobName ||
                    newEntity.ExecuteType != oldEntity.ExecuteType
                    )
                )
            {
                JobCenter.JobCancel(oldEntity);
                JobCenter.JobStart(newEntity);
                return;
            }

            // 如果CRON表达式有数据，就按最新的来
            if (!string.IsNullOrWhiteSpace(newEntity.CronExpression))
                newEntity.NextStartTime = SpareTime.GetCronNextOccurrence(newEntity.CronExpression).GetValueOrDefault().DateTime;
            
        }
    }
}
